package com.example.javaeefinal.Service.Imp;

import com.example.javaeefinal.Mapper.UserMapper;
import com.example.javaeefinal.Service.UserService;
import com.example.javaeefinal.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImp implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findPasswordByUserName(String username) {
        User u = userMapper.findPasswordByUserName(username);
        return u;
    }

    @Override
    public void register(String username, String password) {
        userMapper.add(username, password);
    }


    @Override
    public Map<String, Object> findUserList(int type, String value, int pageSize, int pageNumber) {
        int maxRowsNumber = userMapper.countUser();
        int rowsNumber = (pageNumber - 1) * pageSize  >= maxRowsNumber ? 0 : (pageNumber - 1) * pageSize;
        int nowPage=(pageNumber - 1) * pageSize>= maxRowsNumber?1:pageNumber;
        List<User> userList;

        rowsNumber = rowsNumber >= maxRowsNumber ? 0 : rowsNumber;
       int maxPage = maxRowsNumber % pageSize == 0 ? (maxRowsNumber / pageSize) : (maxRowsNumber / pageSize + 1);
        if (type == 0) {
            userList = userMapper.findUserListByUsername(value, pageSize, rowsNumber);
        } else {
            userList = userMapper.findUserListByPhoneNumber(value, pageSize, rowsNumber);
        }
        //复合的json构造
        Map<String, Object> data = new HashMap<>();
        data.put("data", userList);
        data.put("maxPage", maxPage);
        data.put("nowPage",nowPage);
        return data;
    }

    @Override
    public User findUserById(int id) {
        return userMapper.findUserById(id);
    }

    @Override
    public void updateUserAndInfoById(User user) {
        userMapper.updateUserById(user);
        if (user.getPhone() != null || user.getMail() != null || user.getDescribe() != null) {
            userMapper.updateUserInfoById(user);
        }
    }

    @Override
    public User isExistByUid(int userId) {
        User u = userMapper.isExistByUid(userId);
        return u;
    }

    @Override
    public void addRole(int userId, int roleId) {
        userMapper.addRole(userId, roleId);
    }

    @Override
    public List<User> findUsersRid(int roleId) {
        return userMapper.findUsersRid(roleId);
    }

    @Override
    public void delRole(int userId, int roleId) {
        userMapper.delRole(userId, roleId);
    }

    @Override
    public int countUser() {
        return userMapper.countUser();
    }
}
